package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import dao.OrdersDao;
import po.OrderItems;
import po.Orders;

@Repository("ordersDao")
public class OrdersDaoImpl implements OrdersDao{
	@PersistenceContext(name="un")
	private EntityManager em;

	@Override
	public List<Orders> findOrdersByCid(String cid) {
		String jpql="from Orders o where o.client.cid=:cid order by o.dt desc";
		return em.createQuery(jpql).setParameter("cid", cid).getResultList();
	}
	@Override
	public String updateOrders(Orders orders) {
		em.merge(orders);
		
		return orders.getoId();
	}

	@Override
	public Orders findOrder(String oid) {
		Orders orders=em.find(Orders.class, oid);
		return orders;
	}

	@Override
	public String addOrder(Orders orders) {
		List<OrderItems> orderItems=orders.getOrderItems();
		for (OrderItems orderItems2 : orderItems) {
			orderItems2.setOrder(orders);
		}
		em.persist(orders);
		return orders.getoId();
	}
	@Override
	public List<Orders> findOrdersByMid(String mid) {
		String jpql="from Orders o where o.merchant.mId=:mid order by o.dt desc";
		return em.createQuery(jpql).setParameter("mid", mid).getResultList();
	}
	@Override
	public List<Orders> findWaitingForReceiveOrdersByCid(String cid) {
		String jpql="from Orders o where o.client.cid=:cid and o.receive=:receive and (o.status=:status1 or o.status=:status0) order by o.dt desc";
		return em.createQuery(jpql).setParameter("cid", cid).setParameter("receive", 0).setParameter("status1", 1).setParameter("status0", 0).getResultList();
	}
	@Override
	public List<Orders> findHistoricalOrdersByCid(String cid) {
		String jpql="from Orders o where o.client.cid=:cid and (o.receive=:receive or o.status=:status) order by o.dt desc";
		return em.createQuery(jpql).setParameter("cid", cid).setParameter("receive", 1).setParameter("status", 2).getResultList();
	}
	@Override
	public List<Orders> findWaitingForPickOrdersVoByCid(String cid) {
		String jpql="from Orders o where o.client.cid=:cid and o.status=:status order by o.dt desc";
		return em.createQuery(jpql).setParameter("cid", cid).setParameter("status", 0).getResultList();
	}
}
//0 wait 1 already 2 refuse 8:41 PM 
//0 not confirm  1 confirm 
